package com.taokatao.cardmee.business.cardcrud;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

import com.taokatao.cardmee.Utils;


public class PatternEditText extends EditText {
    private final char CHAR_SPACE = ' ';
    private final TextWatcher tw = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Utils.loge("PatternEditText onTextChanged s %s:", s);
            String sWithoutSpace = s.toString().replaceAll(String.valueOf(CHAR_SPACE), "");
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i <= sWithoutSpace.length(); i++) {
                sb.append(sWithoutSpace.charAt(i - 1));
                if (i % 3 == 0) {
                    sb.append(CHAR_SPACE);
                }
            }
            setTextAvoidCallback(sb.toString().trim());
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    public PatternEditText(Context context) {
        this(context, null);
    }


    public PatternEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        addTextChangedListener(tw);
    }

    private void setTextAvoidCallback(CharSequence text) {
        removeTextChangedListener(tw);
        setText(text);
        setSelection(TextUtils.isEmpty(text) ? 0 : text.length());
        addTextChangedListener(tw);
    }

    public String getTextWithoutCharSpace() {
        String beforeWithout = getText().toString();
        return beforeWithout.replaceAll(String.valueOf(CHAR_SPACE), "");
    }
}
